import React, { useEffect, useRef, useState } from "react";
import { Search } from "react-vant";
import ShoppItem from "../../components/shoppItem";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { useSelector } from 'react-redux'
import './style.scss'
const Index = () => {
  const searchRef = useRef();
  // 列表数据
  const [list, setList] = useState([]);
  // 获取列表数据
  const fetchList = async (wd = "") => {
    const resp = await axios.get("/api/list", { params: { wd } });
    const { code, data, message } = resp.data;
    if (code === 200) {
      setList(resp.data.data);
    }
  };
  const navigate = useNavigate();
  // 是否置灰
  const getIsActive = (v) => {
    return userBrowerList.some((item) => item.baseSpuId === v.baseSpuId);
  };
  // 获取浏览记录
  const userBrowerList = useSelector((state) => state.user.userBrowerList);
  useEffect(() => {
    searchRef.current.focus();
  }, []);
  return (
    <div>
      <Search placeholder="请输入内容" ref={searchRef} onSearch={(value) => fetchList(value)}></Search>
      <div className="list">
        {list.map(({ product }, i) => {
          return (
            <ShoppItem
              key={i}
              product={product}
              onClick={() =>
                navigate("/detail/" + product.baseSpuId, {
                  state: product,
                })
              }
              isActive={getIsActive(product)}
            ></ShoppItem>
          );
        })}
      </div>
    </div>
  );
};

export default Index;
